{% extends "base.html" %}

{% block title %}智能问答 - 乳腺癌预测系统{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h4 class="mb-0">
                        <i class="fas fa-robot"></i> 智能医学问答系统
                    </h4>
                    <small>基于RAG技术的乳腺癌相关知识问答</small>
                </div>
                <div class="card-body">
                    <!-- 问答界面 -->
                    <div class="row">
                        <div class="col-md-8">
                            <div class="chat-container" style="height: 500px; overflow-y: auto; border: 1px solid #ddd; padding: 15px; margin-bottom: 20px;">
                                <div id="chat-messages">
                                    <div class="message bot-message">
                                        <div class="message-content">
                                            <strong>医学助手：</strong>您好！我是您的医学知识助手，可以回答关于乳腺癌的相关问题。请随时提问！
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 输入框 -->
                            <div class="input-group">
                                <input type="text" id="question-input" class="form-control" placeholder="请输入您的问题..." maxlength="500">
                                <div class="input-group-append">
                                    <button class="btn btn-primary" id="ask-btn">
                                        <i class="fas fa-paper-plane"></i> 提问
                                    </button>
                                </div>
                            </div>
                            
                            <!-- 快捷问题 -->
                            <div class="mt-3">
                                <h6>常见问题：</h6>
                                <div class="quick-questions">
                                    <button class="btn btn-outline-secondary btn-sm quick-question" data-question="乳腺癌有哪些症状？">乳腺癌症状</button>
                                    <button class="btn btn-outline-secondary btn-sm quick-question" data-question="如何预防乳腺癌？">预防方法</button>
                                    <button class="btn btn-outline-secondary btn-sm quick-question" data-question="乳腺癌如何治疗？">治疗方法</button>
                                    <button class="btn btn-outline-secondary btn-sm quick-question" data-question="乳腺癌分期是什么意思？">分期说明</button>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <!-- 知识搜索 -->
                            <div class="card mb-3">
                                <div class="card-header">
                                    <h6 class="mb-0">知识搜索</h6>
                                </div>
                                <div class="card-body">
                                    <div class="input-group mb-2">
                                        <input type="text" id="search-input" class="form-control" placeholder="搜索关键词...">
                                        <div class="input-group-append">
                                            <button class="btn btn-outline-primary" id="search-btn">
                                                <i class="fas fa-search"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div id="search-results"></div>
                                </div>
                            </div>
                            
                            <!-- 知识分类 -->
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">知识分类</h6>
                                </div>
                                <div class="card-body">
                                    <div id="knowledge-categories">
                                        <div class="text-center">
                                            <div class="spinner-border spinner-border-sm" role="status">
                                                <span class="sr-only">加载中...</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.message {
    margin-bottom: 15px;
    padding: 10px;
    border-radius: 10px;
}

.user-message {
    background-color: #007bff;
    color: white;
    margin-left: 20%;
}

.bot-message {
    background-color: #f8f9fa;
    color: #333;
    margin-right: 20%;
}

.message-content {
    word-wrap: break-word;
}

.quick-questions {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.quick-question {
    margin: 2px;
}

.search-result {
    border: 1px solid #ddd;
    border-radius: 5px;
    padding: 10px;
    margin-bottom: 10px;
    background-color: #f9f9f9;
}

.search-result h6 {
    color: #007bff;
    margin-bottom: 5px;
}

.search-result .similarity {
    font-size: 0.8em;
    color: #666;
}

.category-item {
    cursor: pointer;
    padding: 5px 10px;
    margin: 2px 0;
    border-radius: 3px;
    background-color: #f8f9fa;
    border: 1px solid #dee2e6;
}

.category-item:hover {
    background-color: #e9ecef;
}

.loading {
    text-align: center;
    padding: 20px;
    color: #666;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const questionInput = document.getElementById('question-input');
    const askBtn = document.getElementById('ask-btn');
    const chatMessages = document.getElementById('chat-messages');
    const searchInput = document.getElementById('search-input');
    const searchBtn = document.getElementById('search-btn');
    const searchResults = document.getElementById('search-results');
    const categoriesDiv = document.getElementById('knowledge-categories');
    
    // 加载知识分类
    loadCategories();
    
    // 提问功能
    askBtn.addEventListener('click', askQuestion);
    questionInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            askQuestion();
        }
    });
    
    // 快捷问题
    document.querySelectorAll('.quick-question').forEach(btn => {
        btn.addEventListener('click', function() {
            const question = this.getAttribute('data-question');
            questionInput.value = question;
            askQuestion();
        });
    });
    
    // 搜索功能
    searchBtn.addEventListener('click', searchKnowledge);
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchKnowledge();
        }
    });
    
    function askQuestion() {
        const question = questionInput.value.trim();
        if (!question) return;
        
        // 显示用户问题
        addMessage(question, 'user');
        questionInput.value = '';
        
        // 显示加载状态
        const loadingId = addMessage('正在思考中...', 'bot', true);
        
        // 发送请求
        fetch('/api/rag/ask', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ question: question })
        })
        .then(response => response.json())
        .then(data => {
            // 移除加载状态
            removeMessage(loadingId);
            
            if (data.error) {
                addMessage('抱歉，系统出现错误：' + data.error, 'bot');
            } else {
                let answer = data.answer;
                if (data.sources && data.sources.length > 0) {
                    answer += '\n\n参考来源：';
                    data.sources.forEach((source, index) => {
                        answer += `\n${index + 1}. ${source.title} (${source.category})`;
                    });
                }
                addMessage(answer, 'bot');
            }
        })
        .catch(error => {
            removeMessage(loadingId);
            addMessage('抱歉，网络连接出现问题，请稍后重试。', 'bot');
            console.error('Error:', error);
        });
    }
    
    function addMessage(content, type, isLoading = false) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}-message`;
        if (isLoading) {
            messageDiv.id = 'loading-' + Date.now();
        }
        
        const contentDiv = document.createElement('div');
        contentDiv.className = 'message-content';
        contentDiv.innerHTML = type === 'user' ? content : content.replace(/\n/g, '<br>');
        messageDiv.appendChild(contentDiv);
        
        chatMessages.appendChild(messageDiv);
        chatMessages.scrollTop = chatMessages.scrollHeight;
        
        return messageDiv.id;
    }
    
    function removeMessage(messageId) {
        const message = document.getElementById(messageId);
        if (message) {
            message.remove();
        }
    }
    
    function searchKnowledge() {
        const query = searchInput.value.trim();
        if (!query) return;
        
        searchResults.innerHTML = '<div class="loading">搜索中...</div>';
        
        fetch('/api/rag/search', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ query: query, top_k: 5 })
        })
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                searchResults.innerHTML = '<div class="text-danger">搜索失败：' + data.error + '</div>';
            } else {
                displaySearchResults(data.results);
            }
        })
        .catch(error => {
            searchResults.innerHTML = '<div class="text-danger">搜索失败，请稍后重试</div>';
            console.error('Error:', error);
        });
    }
    
    function displaySearchResults(results) {
        if (results.length === 0) {
            searchResults.innerHTML = '<div class="text-muted">未找到相关知识</div>';
            return;
        }
        
        let html = '';
        results.forEach(result => {
            html += `
                <div class="search-result">
                    <h6>${result.title}</h6>
                    <p>${result.content}</p>
                    <div class="similarity">相关度: ${(result.similarity * 100).toFixed(1)}% | 分类: ${result.category}</div>
                </div>
            `;
        });
        searchResults.innerHTML = html;
    }
    
    function loadCategories() {
        fetch('/api/rag/categories')
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                categoriesDiv.innerHTML = '<div class="text-danger">加载失败：' + data.error + '</div>';
            } else {
                displayCategories(data.categories);
            }
        })
        .catch(error => {
            categoriesDiv.innerHTML = '<div class="text-danger">加载失败，请稍后重试</div>';
            console.error('Error:', error);
        });
    }
    
    function displayCategories(categories) {
        let html = '';
        categories.forEach(category => {
            html += `<div class="category-item" onclick="loadCategoryKnowledge('${category}')">${category}</div>`;
        });
        categoriesDiv.innerHTML = html;
    }
    
    window.loadCategoryKnowledge = function(category) {
        searchResults.innerHTML = '<div class="loading">加载中...</div>';
        
        fetch(`/api/rag/knowledge/${encodeURIComponent(category)}`)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                searchResults.innerHTML = '<div class="text-danger">加载失败：' + data.error + '</div>';
            } else {
                displaySearchResults(data.knowledge);
            }
        })
        .catch(error => {
            searchResults.innerHTML = '<div class="text-danger">加载失败，请稍后重试</div>';
            console.error('Error:', error);
        });
    };
});
</script>
{% endblock %}
